package com.go.where.family.api.parse;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Parser {
	private static List<BeanVO> beanList = new ArrayList<BeanVO>();

	public List<BeanVO> getBeanList() throws Exception {
		if (beanList.isEmpty())
			beanList = this.parser();
		return beanList;
	}

	@SuppressWarnings("unchecked")
	private List<BeanVO> parser() throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read(Parser.class.getClassLoader()
				.getResourceAsStream("bean.xml"));
		Document doc = document.getDocument();
		Element root = doc.getRootElement();
		List<BeanVO> map = new ArrayList<BeanVO>();
		for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
			Element element = (Element) i.next();
			BeanVO bean = new BeanVO();
			List<Attribute> list = element.attributes();
			for (Attribute att : list) {
				if ("class".equals(att.getName()))
					bean.setClasses(att.getValue());
				else if ("urlPattern".equals(att.getName()))
					bean.setUrlPattern(att.getValue());
				// else if ("ip".equals(att.getName()))
				// bean.setIp(att.getValue());
				// else if ("port".equals(att.getName()))
				// bean.setPort(att.getValue());
			}
			if (bean.getClasses() != null && bean.getUrlPattern() != null)
				map.add(bean);
		}
		return map;
	}
}
